# coding: utf-8
"""
ws-agent resources
============
"""
import logging
import traceback

from flask_marshmallow import base_fields
from flask_restplus import Resource

from app.extensions.api import http_exceptions
from app.modules import apis
from app.modules.api.response import default
from app.modules.common.Errors import ServiceError
from app.modules.menu import service
from flask_restplus_patched import Parameters
from flask_restplus_patched import api

log = logging.getLogger(__name__)

api = apis[__name__]


class RecreateParam(Parameters):
    menu_items = base_fields.String(
        description="嵌套的menu json格式",
        missing=None,  # default value
        required=True,
    )

    workspace = base_fields.String(
        description="jsx代码的工作空间标志, 目前填default或者空都行",
        missing='default',
        required=True,
    )


class UpdateParam(Parameters):
    path = base_fields.String(
        description="菜单路径 例如:OMS/WarehouseManage",
        missing=None,  # default value
        required=True,
    )

    parent_menu_id = base_fields.String(
        description="上级菜单ID,顶层菜单时传递空",
        missing=None,  # default value
        required=False,
    )

    menu_id = base_fields.String(
        description="菜单id",
        missing=None,  # default value
        required=True,
    )

    index = base_fields.Integer(
        description="菜单位置,从0开始",
        missing='0',  # default value
        required=True,
    )

    title = base_fields.String(
        description="标题,菜单的显示标题",
        missing='新建菜单项',  # default value
        required=True,
    )

    is_front = base_fields.Boolean(
        description="是否前置显示,填写true即可",
        missing=True,  # default value
        required=True,
    )

    is_item = base_fields.Boolean(
        description="是否是最下层菜单项",
        required=True,
    )

    workspace = base_fields.String(
        description="jsx代码的工作空间标志, 目前填default或者空都行",
        missing='default',
        required=True,
    )


class DeleteParam(Parameters):
    menu_id = base_fields.String(
        description="菜单id, 该功能一般用于刚刚添加的菜单, 并禁止删除有已经有页面的菜单",
        missing=None,  # default value
        required=True,
    )
    workspace = base_fields.String(
        description="jsx代码的工作空间标志, 目前填default或者空都行",
        missing='default',  # default value
        required=True,
    )


@api.route('/recreate', methods=['GET', 'POST'])
@api.response(
    code=http_exceptions.UnprocessableEntity.code,
    description="can't create menu.",
)
class Recreate(Resource):
    @api.parameters(RecreateParam())
    @api.marshal_with(default(api))
    def post(self, args):

        # 2. 处理菜单文件
        try:
            menu_items = args['menu_items']
            workspace = args['workspace']
            service.recreate(menu_items=menu_items, workspace=workspace)
        except ServiceError as e:

            traceback.print_stack()

            return {'isSuccess': False, 'msg': e.msg}
        except BaseException as e:
            log.error(e)
            return {'isSuccess': False, 'msg': traceback.format_exc()}

        return {'isSuccess': True, 'msg': 'success!'}


# @api.route('/update')
# @api.response(
#     code=http_exceptions.UnprocessableEntity.code,
#     description="menu not found.",
# )
class Update(Resource):
    @api.parameters(UpdateParam())
    @api.marshal_with(default(api))
    def get(self, args):

        # 2. 处理菜单文件
        try:

            menu_id = args['menu_id']
            path = args['path']
            parent_menu_id = args['parent_menu_id']
            index = args['index']
            title = args['title']
            is_front = args['is_front']
            is_action = args['is_action']
            workspace = args['workspace']

            service.update(path=path, parent_menu_id=parent_menu_id,
                           menu_id=menu_id, index=index,
                           title=title,
                           is_front=is_front,
                           is_item=is_action, workspace=workspace)
        except ServiceError as e:

            traceback.print_stack()

            return {'isSuccess': False, 'msg': e.msg}
        except BaseException as e:
            log.error(e)
            return {'isSuccess': False, 'msg': traceback.format_exc()}

        return {'isSuccess': True, 'msg': 'success!'}


# @api.route('/delete')
# @api.response(
#     code=http_exceptions.UnprocessableEntity.code,
#     description="The menu contains pages, can not deleted.",
# )
class Delete(Resource):
    @api.parameters(DeleteParam())
    @api.marshal_with(default(api))
    def get(self, args):

        try:

            menu_id = args['menu_id']
            workspace = args['workspace']

            service.remove(menu_id=menu_id, workspace=workspace)

        except ServiceError as e:

            return {'isSuccess': False, 'msg': traceback.format_exc()}

        except BaseException as e:

            log.error(e)

            return {'isSuccess': False, 'msg': traceback.format_exc()}

        return {'isSuccess': True, 'msg': 'success!'}
